

# token就是认证后返回的token
# user就是认证后的user
#
from django.contrib.auth.backends import ModelBackend
import re

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'username':user.username,
        'user_id':user.id

    }


def get_user_by_mobile(username):
    try:
        if re.match(r'1[3-9]\d{9}',username):
            #         匹配成功就根据手机号查询数据库
            user=User.objects.get(mobile=username)
        else:
            user=User.objects.get(username=username)
    except User.DoesExist:
        user=None
    return user
class UserMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None,**kwargs):
    #     匹配手机号
    #     try:
    #         if re.match(r'1[3-9]\d{9}',username):
    #     #         匹配成功就根据手机号查询数据库
    #             user=User.objects.get(mobile=username)
    #         else:
    #             user=User.objects.get(username=username)
    #     except User.DoesExist:
    #         user=None
        user=get_user_by_mobile(username)
        if user is not None and user.check_password(password):
            return user
